<template>
  <view class="login-page">
    <!-- 顶部蓝色背景图区域 -->
    <view class="top-bg" style="position: relative;">
      <view class="welcome">欢迎来到车联网服务平台商家端</view>
      <image class="hero" src="/static/车联网服务商家端-00登录_slices/组 6(1).png" mode="widthFix"></image>
    </view>

    <!-- 下方内容：全宽并占满剩余空间 -->
    <view class="content" style="position: absolute;top: 320rpx;padding-top: 100rpx;height: 100vh;">
      <view class="input-row">
        <input class="text-input" v-model="phone" type="number" placeholder="手机号登陆" placeholder-style="color:#c0c4cc" />
      </view>

      <view class="input-row code-row">
        <input class="text-input" v-model="code" placeholder="输入验证码" placeholder-style="color:#c0c4cc" />
        <view class="code-btn" :class="{disabled: countdown>0}" @tap="sendCode">{{ countdown>0 ? countdown + 's' : '获取验证码' }}</view>
      </view>

      <view v-if="sendSuccessMsg" class="success-tip">{{ sendSuccessMsg }}</view>

      <view class="register-row">
        <text class="register" @tap="goRegister">立即注册 ></text>
      </view>

      <view class="login-btn" @tap="login">登录</view>
    </view>
  </view>
 </template>

 <script>
 export default {
   data() {
     return {
       phone: '',
       code: '',
       countdown: 0,
      timerId: null,
      sendSuccessMsg: '',
      msgTimerId: null
     }
   },
  methods: {
    // 验证手机号格式
    validatePhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.timerId && clearInterval(this.timerId)
      this.timerId = setInterval(() => {
        if (this.countdown <= 1) {
          clearInterval(this.timerId)
          this.timerId = null
          this.countdown = 0
        } else {
          this.countdown -= 1
        }
      }, 1000)
    },
    
    // 发送验证码
    async sendCode() {
      if (this.countdown > 0) return
      
      // 验证手机号
      if (!this.phone) {
        uni.showToast({ title: '请输入手机号', icon: 'none' })
        return
      }
      
      if (!this.validatePhone(this.phone)) {
        uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' })
        return
      }
      
      // 显示加载状态
      uni.showLoading({ title: '发送中...' })
      
      try {
        // 调用后端API发送验证码（uni.request Promise 返回 [error, res]）
      const [requestError, response] = await uni.request({
        url: '/api/system/sms/sendCode?phoneNumber=' + encodeURIComponent(this.phone),
        method: 'POST'
      })
        
        
        uni.hideLoading()
        
        // 处理响应
        if (!requestError && response && response.statusCode === 200 && response.data) {
          const result = response.data
          
          if (result.code === 200) {
            // 发送成功
            uni.showToast({ 
              title: result.data || '验证码发送成功', 
              icon: 'success',
              duration: 2000
            })
            
            // 开始倒计时
            this.startCountdown()

            // 页面提示
            this.sendSuccessMsg = `验证码已发送至 ${this.phone}，请注意查收`
            this.msgTimerId && clearTimeout(this.msgTimerId)
            this.msgTimerId = setTimeout(() => {
              this.sendSuccessMsg = ''
              this.msgTimerId = null
            }, 5000)
            
            // 如果后端返回了验证码（开发环境可能会返回），可以在控制台显示
            if (result.msg && result.msg !== result.data) {
              console.log('验证码：', result.msg)
            }
          } else {
            // 业务错误
            uni.showToast({ 
              title: result.msg || '发送失败', 
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          // HTTP错误
          const networkMsg = (requestError && requestError.errMsg) ? requestError.errMsg : '网络请求失败'
          uni.showToast({ 
            title: networkMsg, 
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('发送验证码失败：', error)
        
        // 根据错误类型给出不同提示
        let errorMsg = '发送失败，请重试'
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络'
          } else if (error.errMsg.includes('fail')) {
            errorMsg = '网络连接失败'
          }
        }
        
        uni.showToast({ 
          title: errorMsg, 
          icon: 'none',
          duration: 2000
        })
        this.sendSuccessMsg = ''
      }
    },
     async login() {
       // 基本校验
       if (!this.phone || !this.code) {
         uni.showToast({ title: '请填写手机号和验证码', icon: 'none' })
         return
       }
       if (!this.validatePhone(this.phone)) {
         uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' })
         return
       }

       uni.showLoading({ title: '登录中...' })
       try {
         const [requestError, response] = await uni.request({
           url: '/api/merchant/shop/login/sms',
           method: 'POST',
           header: { 'Content-Type': 'application/x-www-form-urlencoded' },
           data: { phoneNumber: this.phone, code: this.code }
         })

         uni.hideLoading()

         if (!requestError && response && response.statusCode === 200 && response.data) {
           const result = response.data
           if (result.code === 200 && result.data && result.data.access_token) {
             const token = result.data.access_token
             try {
               this.$store && this.$store.dispatch('saveAuth', {
                 token,
                 userId: result.data.userId,
                 expiresIn: result.data.expires_in
               })
             } catch(e) {}

             uni.showToast({ title: '登录成功', icon: 'success', duration: 1200 })
             setTimeout(() => {
               uni.reLaunch({ url: '/pages/index/index' })
             }, 800)
           } else {
             const msg = (result && result.msg) ? String(result.msg) : ''
             if (msg.includes('验证码')) {
               uni.showToast({ title: '验证码错误', icon: 'none' })
             } else if (msg.includes('不存在') || msg.includes('未注册') || msg.includes('未找到') || msg.includes('没有该账户')) {
               uni.showToast({ title: '没有该账户，请注册后登录', icon: 'none' })
             } else {
               uni.showToast({ title: msg || '登录失败', icon: 'none' })
             }
           }
         } else {
           const networkMsg = (requestError && requestError.errMsg) ? requestError.errMsg : '网络请求失败'
           uni.showToast({ title: networkMsg, icon: 'none' })
         }
       } catch (error) {
         uni.hideLoading()
         uni.showToast({ title: '登录失败，请重试', icon: 'none' })
       }
     },
     goRegister() {
       uni.navigateTo({
         url: '/fk/RegisterPage/index'
       })
     }
   },
   beforeDestroy() {
     this.timerId && clearInterval(this.timerId)
    this.msgTimerId && clearTimeout(this.msgTimerId)
   }
 }
 </script>

 <style scoped>
 .login-page { min-height: 100vh; display: flex; flex-direction: column; background: #f5f7fb; }
 .top-bg {
   height: 380rpx;
   background: url('/static/车联网服务商家端-00登录_slices/组 6.png') no-repeat center/cover;
   position: relative;
   display: flex; align-items: center; justify-content: center;
 }
 .welcome { position: absolute; top: 48rpx; left: 0; right: 0; text-align: center; color: #fff; font-size: 34rpx; }
 .hero { width: 300rpx; z-index: 999; position: absolute; bottom: 20rpx; left: 48%; transform: translateX(-50%); }

 .content {
   flex: 1;
   width: 100%;
   background: #ffffff;
   border-top-left-radius: 40rpx;
   border-top-right-radius: 40rpx;
   margin-top: -16rpx;
   padding: 56rpx 32rpx 48rpx;
     border-top-left-radius: 30px;
     border-top-right-radius: 30px;
   box-sizing: border-box;
 }

 .input-row { 
		display: flex;
		align-items: center; 
			border-bottom: 2rpx solid #e6ebf0; 
			padding: 20rpx 0;
			 width: 80%;
			 margin-left:10% ;
			 }
 .text-input { flex: 1; height: 72rpx; line-height: 72rpx; font-size: 28rpx; color: #333; }

 .code-row { position: relative; }
 .code-btn { padding: 0 24rpx; height: 56rpx; line-height: 56rpx; background: linear-gradient(90deg, #4da3ff, #1677ff); color: #fff; border-radius: 28rpx; font-size: 24rpx; margin-left: 20rpx; }
 .code-btn.disabled { background: #c0c4cc; }

 .register-row { padding: 24rpx 0 12rpx;  margin-left: 10%;}
 .register { color: #1677ff; font-size: 26rpx;  }

 .login-btn { width: 84%; height: 88rpx; line-height: 88rpx; text-align: center; color: #fff; font-size: 30rpx; border-radius: 44rpx; background: linear-gradient(90deg, #3d7eff 0%, #1677ff 100%); box-shadow: 0 12rpx 24rpx rgba(22,119,255,0.35); margin: 32rpx auto 0; }
 </style>